<template>
    <el-card shadow="never">
        <el-form label-position="top" :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="page-form">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
                <el-input v-model="form.description"></el-input>
            </el-form-item>
			<el-form-item label="角色权限" prop="permissions">
                <el-tree ref="tree" :props="treeProps" :data="allPermissions" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="form.permissions">
                </el-tree>
            </el-form-item>

			<el-form-item>
				<el-button  @click="$router.go(-1)">取消</el-button>
				<el-button  type="primary" @click="saveRole()">确认</el-button>
			</el-form-item>
        </el-form>
    </el-card>
</template>

<script>
import {queryPermissionTree,editRole,getRolePermission} from '@/api/role'
export default {
    name: "role-add",
    data() {
        return {
			allPermissions:[],
			treeProps: {
                children: "children",
                label: "label",
            },
            form: {
				role_id:"",
                name: "",
                description: "",
                permissions: [],
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入角色名称",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
	mounted(){
		this.form.role_id=this.$route.params.id
		queryPermissionTree().then(res=>{
			this.allPermissions=res.data
			getRolePermission({role_id:this.form.role_id}).then(res2=>{
				this.form.permissions=res2.data.map(item=>item.id)
			})
		})
	},
	methods:{
		saveRole() {
            this.form.permissions = this.$refs.tree.getCheckedKeys();
            var form = JSON.parse(JSON.stringify(this.form));
            form.permissions = this.form.permissions.concat(
                this.$refs.tree.getHalfCheckedKeys()
            );
			console.log(form);
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    editRole(form).then((res) => {
						this.$message.success("角色编辑成功")
                        this.$router.go(-1)
                    });
                }
            });
        },

	}
};
</script>

<style>
</style>
